package com.newlink.building.userinfo.activity

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_DeviceType
import com.newlink.building.common_base.ext.clickDelay
import com.newlink.building.common_base.model.bean.AuthResponseBody
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.DeviceListRequest
import com.newlink.building.common_base.model.bean.FamilyListData
import com.newlink.building.common_base.model.bean.FamilyManagementListData1
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.widget.CustomInputDialog
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.activity.Module_UserInfo_AuthCardAddActivityNL.Companion.EXTRA_DATA
import com.newlink.building.userinfo.activity.Module_UserInfo_AuthCardAddActivityNL.Companion.EXTRA_MODE
import com.newlink.building.userinfo.adapter.Module_UserInfo_AreaSelectionAdapter
import com.newlink.building.userinfo.adapter.Module_UserInfo_MemberPickAdapter
import com.newlink.building.userinfo.bean.CardInfo
import com.newlink.building.userinfo.bean.CardModifyInfo
import com.newlink.building.userinfo.bean.Module_UserInfo_CheckBean
import com.newlink.building.userinfo.databinding.ActivityAuthCardBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_AuthCardPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AuthCardContract
import org.jetbrains.anko.textColorResource


const val TYPE_NAME: Int = 10000
const val TYPE_CARD_NUMBER: Int = 10001


/**
 * @Author: Jake
 * @Date: 2023-12-14
 * @Description:
 */
class AuthCardActivityNL
    : NL_BaseMvpActivity<Module_UserInfo_AuthCardContract.View, Module_UserInfo_AuthCardContract.Presenter>(),
    Module_UserInfo_AuthCardContract.View {

    private var mCardName: String = ""
    private var mCardId: String = ""
    private var mCardNumber: String = ""
    private var mNeedShowDialog = false
    private var deviceBeans = mutableListOf<Module_UserInfo_CheckBean>()
    private var bottomSheetDialog: BottomSheetDialog? = null
    private var mSelectItem: MutableList<Module_UserInfo_CheckBean>? = null

    private var mWaitProgressDialog: ProgressDialog? = null
    private val MAX_LIMIT = 1000

    private var mPageMode = 0
    private var mAuthResponseBody: AuthResponseBody? = null

    private var mFamilyListData: MutableList<FamilyManagementListData1> = mutableListOf()

    override fun createPresenter(): Module_UserInfo_AuthCardContract.Presenter = Module_UserInfo_AuthCardPresenter()

//    override fun attachLayoutRes(): Int = R.layout.activity_auth_card

    private lateinit var mBinding: ActivityAuthCardBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityAuthCardBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        mPageMode = intent.getIntExtra(EXTRA_MODE, 0)
        if (mPageMode == 1) {
            mAuthResponseBody = intent.getSerializableExtra(EXTRA_DATA) as AuthResponseBody?
            mAuthResponseBody?.let {
                mSelectItem = mutableListOf()
                for (i in 0 until it.devNames.size) {
                    if (it.devNames[i].isNotEmpty() && it.macs[i].isNotEmpty()) {
                        mSelectItem?.add(
                            Module_UserInfo_CheckBean(
                                it.devNames[i],
                                it.macs[i],
                                Base_DeviceType.DOORPHONE.code,
                                true
                            )
                        )
                    }
                }
            }
        }

        showWaitingDialog(getString(R.string.auth_face_load_area))
        mPresenter?.getFamilyMember(accessToken)

    }

    override fun initView() {

        mBinding.authCardName.setOnClickListener {
            showFamilySelectDialog()
        }

        mBinding.authCardNumber.setOnClickListener {
            showCustomInputDialog(
                getString(R.string.auth_card_input_number),
                TYPE_CARD_NUMBER,
                EditorInfo.TYPE_CLASS_NUMBER
            )
        }

        mBinding.authCardArea.clickDelay {
            if (deviceBeans.size == 0) {
                NLog.e("[jake]... click is auth_card_area")
                showWaitingDialog(getString(R.string.auth_face_load_area))
                mNeedShowDialog = true
                mPresenter?.getAvailableArea(
                    DeviceListRequest(accessToken, 1, MAX_LIMIT, "", null)
                )
            } else {
                NLog.e("[jake]... show area dialog")
                if (bottomSheetDialog == null || bottomSheetDialog?.isShowing == false) {

                    if (mPageMode == 1 && mAuthResponseBody != null && mAuthResponseBody?.devNames?.isNotEmpty() == true) {
                        NLog.e("[jake]... 1111111111111g")
                        for (device in deviceBeans) {
                            device.isChecked = device.name in mAuthResponseBody?.devNames!!
                        }
                        deviceBeans.forEach {
                            NLog.e("[jake]... >>>>>>>>> ${it.name} :: ${it.isChecked}")
                        }

                    } else {
                        if (!isFirstShow) {
                            //不是第一次显示,要根据选择的内容区分选中状态
                            deviceBeans.forEach {
                                it.isChecked = false
                                mSelectItem?.forEach { selectItem ->
                                    if (selectItem.name == it.name) {
                                        it.isChecked = true
                                    }
                                }
                            }
                        } else {
                            deviceBeans.forEach { it.isChecked = true }
                        }
                        NLog.e("[jake]... 222222222222")
                    }
                    showBottomSheetDialog(this, deviceBeans)

                }
            }
        }

        mBinding.btnAuthCardSubmit.clickDelay {
            if (mCardName.isEmpty()) {
                ToastUtils.showTextToast(
                    this@AuthCardActivityNL,
                    getString(R.string.auth_card_name_not_input_warning)
                )
                return@clickDelay
            }

            if (mCardNumber.isEmpty()) {
                ToastUtils.showTextToast(
                    this@AuthCardActivityNL,
                    getString(R.string.auth_card_number_not_input_warning)
                )
                return@clickDelay
            }
            NLog.e("[jake]... mSelectItem is $mSelectItem")
            if (mSelectItem == null || mSelectItem?.size == 0) {
                ToastUtils.showTextToast(
                    this@AuthCardActivityNL,
                    getString(R.string.auth_card_area_not_input_warning)
                )
                return@clickDelay
            }

            val availableArea = mutableListOf<String>()

            for (item in mSelectItem!!) {
                availableArea.add(item.value)
            }

            NLog.e("[jake]... cardName is $mCardName")
            NLog.e("[jake]... cardId is $mCardId")
            NLog.e("[jake]... cardNumber is $mCardNumber")
            NLog.e("[jake]... availableArea is $availableArea")
            NLog.e("[jake]... mPageMode is $mPageMode")
            if (mCardName.isNotEmpty() && mCardNumber.isNotEmpty() && availableArea.isNotEmpty()) {
                if (mPageMode == 0) {
                    if (mCardId.isEmpty()) {
                        ToastUtils.showTextToast(
                            this@AuthCardActivityNL,
                            getString(R.string.auth_card_not_input_warning)
                        )
                        return@clickDelay
                    }
                    mPresenter?.addCardInformation(
                        accessToken, "$userId", CardInfo(
                            name = mCardName,
                            userId = mCardId,
                            cardNum = mCardNumber,
                            availableArea = availableArea
                        )
                    )
                } else {
                    mPresenter?.modifyCardInformation(
                        accessToken, CardModifyInfo(
                            id = mAuthResponseBody?.id.orEmpty(),
                            availableArea = availableArea
                        )
                    )
                }
            } else {
                ToastUtils.showTextToast(
                    this@AuthCardActivityNL,
                    getString(R.string.auth_card_not_input_warning)
                )
            }
        }

        if (mPageMode == 1) {
            // edit
            mCardName = mAuthResponseBody?.keyName.orEmpty()
            mCardNumber = mAuthResponseBody?.keyInfo.orEmpty()
            mBinding.tvAuthCardName.text = mCardName
            mBinding.tvAuthCardNumber.text = mCardNumber
            mBinding.tvAuthCardName.textColorResource = R.color.grey_color
            mBinding.tvAuthCardNumber.textColorResource = R.color.grey_color
            mBinding.authCardName.isClickable = false
            mBinding.authCardNumber.isClickable = false
            mBinding.tvAuthCardArea.textColorResource = R.color.black85
            if (mAuthResponseBody?.devNames?.isNotEmpty() == true) {
                mBinding.tvAuthCardArea.visibility = View.VISIBLE
                mBinding.tvAuthCardAreaHint.visibility = View.GONE
                mBinding.tvAuthCardArea.text = mAuthResponseBody?.devNames?.joinToString(",")
                var devNameStr = ""
                for ((index, devName) in mAuthResponseBody!!.devNames.withIndex()) {
                    NLog.e("<jake> .. ......AREA:: : $devName")
                    val name =
                        if (devName.length > 16) {
                            devName.substring(0, 15).plus("...")
                        } else {
                            devName
                        }
                    devNameStr += if (index == mAuthResponseBody!!.devNames!!.size - 1) {
                        name
                    } else {
                        "$name/"
                    }

                }
                mBinding.tvAuthCardArea.text = devNameStr
            } else {
                mBinding.tvAuthCardArea.visibility = View.GONE
                mBinding.tvAuthCardAreaHint.visibility = View.VISIBLE
            }

            findViewById<TextView>(R.id.tv_title_bar_center).text =
                getString(R.string.auth_card_input_title_modify)
        } else {
            findViewById<TextView>(R.id.tv_title_bar_center).text =
                getString(R.string.auth_card_input_title)
            mBinding.tvAuthCardName.textColorResource = R.color.black85
            mBinding.tvAuthCardNumber.textColorResource = R.color.black85
            mBinding.tvAuthCardArea.textColorResource = R.color.black85
        }
    }

    override fun refreshDeviceList(total: Int, list: MutableList<DeviceData>) {
        hideLoading()
        if (bottomSheetDialog != null && bottomSheetDialog?.isShowing == true) {
            //如果当前dialog正在显示，则不刷新
            return
        }
        NLog.e("[jake]... refreshDeviceList .....")
        deviceBeans.clear()
        for (item in list) {
            if (item.devType == Base_DeviceType.DOORPHONE.code) {
                deviceBeans.add(Module_UserInfo_CheckBean(item.devName.orEmpty(), item.mac, 0, true))
            }
        }
        if (mNeedShowDialog) {
            mNeedShowDialog = false
            NLog.e("[jake] .. ${mAuthResponseBody?.devNames}")
            if (mPageMode == 1 && mAuthResponseBody != null && mAuthResponseBody?.devNames?.isNotEmpty() == true) {
                for (device in deviceBeans) {
                    device.isChecked = false
                    if (device.name in mAuthResponseBody?.devNames!!) {
                        device.isChecked = true
                    }
                }
            }
            showBottomSheetDialog(this, deviceBeans)
        }
    }

    override fun onAddCardSuccess() {
        setResult(100001)
        ToastUtils.showTextToast(this@AuthCardActivityNL, getString(R.string.default_add_success))
        finish()
    }

    override fun onAddCardFailed(msg: String) {
        NLog.e("[jake]... onAddCardFailed : $msg")
        ToastUtils.showTextToast(this@AuthCardActivityNL, msg)
    }

    override fun onModifyCardSuccess() {
        setResult(100001)
        ToastUtils.showTextToast(this@AuthCardActivityNL, getString(R.string.default_change_success))
        finish()
    }

    override fun onModifyCardFailed(msg: String) {
        NLog.e("[jake]... onModifyCardFailed : $msg")
        ToastUtils.showTextToast(this@AuthCardActivityNL, msg)
    }

    override fun onGetFamilyMemberSuccess(data: FamilyListData?) {
        mFamilyListData = data?.list!!
        mPresenter?.getAvailableArea(
            DeviceListRequest(accessToken, 1, MAX_LIMIT, "", null)
        )
    }

    override fun onGetFamilyMemberFailed(msg: String) {
        hideLoading()
    }

    private fun showFamilySelectDialog() {
        val popupWindow = PopupWindow(this)
        val view: View = LayoutInflater.from(this).inflate(R.layout.popup_member_pick, null)
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(SpaceItemDecoration(this))
        val accountList = mFamilyListData
        val accountPickAdapter = Module_UserInfo_MemberPickAdapter(accountList)
        recyclerView.adapter = accountPickAdapter
        accountPickAdapter.setOnItemChildClickListener { _, _, position ->
            mBinding.tvAuthCardName.text = accountList[position].name
            mCardName = accountList[position].name
            mCardId = accountList[position].id
            popupWindow.dismiss()
        }

        popupWindow.width = mBinding.authCardName.width
        popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow.contentView = view
        popupWindow.isFocusable = true
        popupWindow.setBackgroundDrawable(ColorDrawable(getColor(R.color.transparent)))
        popupWindow.elevation = 3f
        popupWindow.showAsDropDown(mBinding.authCardName, 0, 4)
    }

    private fun showCustomInputDialog(
        tittle: String,
        type: Int,
        inputType: Int = EditorInfo.TYPE_CLASS_TEXT,
    ) {
        val customInputDialog = CustomInputDialog(this@AuthCardActivityNL)
        customInputDialog.setTitle(tittle).setType(type)
            .setText(
                when (type) {
                    TYPE_NAME -> {
                        mCardName.ifEmpty {
                            ""
                        }
                    }

                    TYPE_CARD_NUMBER -> {
                        mCardNumber.ifEmpty {
                            ""
                        }
                    }

                    else -> {
                        ""
                    }
                }
            )
            .setInputType(inputType)
            .setNegativeButton(
                listener = object : CustomInputDialog.OnClickListener {
                    override fun onClick(type: Int, inputText: String) {
                        customInputDialog.dismiss()
                    }
                }
            ).setPositiveButton(
                listener = object : CustomInputDialog.OnClickListener {
                    override fun onClick(type: Int, inputText: String) {
                        when (type) {
                            TYPE_NAME -> {
                                mCardName = inputText
                                mBinding.tvAuthCardName.text = inputText
                            }

                            TYPE_CARD_NUMBER -> {
                                mCardNumber = inputText
                                mBinding.tvAuthCardNumber.text = inputText
                            }
                        }
                        customInputDialog.dismiss()
                    }

                }

            )
        customInputDialog.show()
    }

    private var isFirstShow = true

    @SuppressLint("InflateParams", "MissingInflatedId")
    private fun showBottomSheetDialog(context: Context, cbs: MutableList<Module_UserInfo_CheckBean>) {
        var selectIndex = 0
        bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        bottomSheetDialog?.setCanceledOnTouchOutside(false)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_auth_card_area, null, false)
        val recyclerView = view.findViewById(R.id.recyclerView) as RecyclerView
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            for (item in cbs) {
                item.isChecked = true
            }
            bottomSheetDialog?.dismiss()
        }
        val title = view.findViewById<TextView>(R.id.tv_title)
        title.text = resources.getString(R.string.auth_card_key_input_area)


        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            if (cbs.size > 0) {
                NLog.e("jake .. ${cbs.size}")
//                mSelectItem = cbs.filter {
//                    it.isChecked
//                }.toMutableList()
                mSelectItem = cbs.filter { it.isChecked }.toMutableList()

                isFirstShow = false
                var names = ""
                if (mAuthResponseBody != null) {
                    mAuthResponseBody?.devNames?.clear()
                }
                for ((index, item) in mSelectItem!!.withIndex()) {

                    if (mAuthResponseBody != null) {
                        mAuthResponseBody?.devNames?.add(item.name)
                    }
                    var tempName = item.name
                    if (tempName.length > 16) {
                        tempName = tempName.substring(0, 15).plus("...")
                    }
                    names += if (index == mSelectItem!!.size - 1) {
                        tempName
                    } else {
                        "$tempName/"
                    }
                }
                NLog.e("jake ..===,> ( $names )")
                if (names.isNotEmpty()) {
                    if (mBinding.tvAuthCardArea != null) {
                        mBinding.tvAuthCardArea.visibility = View.VISIBLE
                        mBinding.tvAuthCardAreaHint.visibility = View.GONE
                        mBinding.tvAuthCardArea.text = names
                    } else {
                        view.findViewById<TextView>(R.id.tv_auth_card_area).apply {
                            maxLines = 1
                            text = names
                        }
                        view.findViewById<TextView>(R.id.tv_auth_card_area).visibility =
                            View.VISIBLE
                        view.findViewById<TextView>(R.id.tv_auth_card_area_hint).visibility =
                            View.GONE
                    }

                } else {

                    mBinding.tvAuthCardArea.visibility = View.GONE
                    mBinding.tvAuthCardAreaHint.visibility = View.VISIBLE
                }
            }
//            if (data.size > 0) {
//                mSelectItem = data[selectIndex]
////                tv_auth_card_area.text = mSelectItem?.name
////                for (bean in )
//                tv_auth_card_area.text = mSelectItem?.name
//            }
            bottomSheetDialog?.dismiss()
        }

//        val selectItems = cbs.filter { it.name in selecValues }.toMutableList()
//        NLog.e("[jake].... >>>  select $selectItems")

//        cbs.filter { it.name in selecValues }

        val mAdapter = Module_UserInfo_AreaSelectionAdapter(cbs)
        recyclerView.adapter = mAdapter
        recyclerView.addItemDecoration(SpaceItemDecoration(context))
        mAdapter.setOnItemClickListener { _, _, position ->
            NLog.e("[jake].... card select $position")
            selectIndex = position
            mAdapter.setSelectItem(position)
        }

        bottomSheetDialog?.setContentView(view)
        bottomSheetDialog?.show()
    }

    private fun showWaitingDialog(msg: String) {
        hideWaitingDialog()
        mWaitProgressDialog = DialogUtil.getWaitDialog(this@AuthCardActivityNL, msg)
        mWaitProgressDialog?.setProgressStyle(ProgressDialog.STYLE_SPINNER)
        mWaitProgressDialog?.show()
    }

    private fun hideWaitingDialog() {
        if (mWaitProgressDialog?.isShowing == true) {
            mWaitProgressDialog?.dismiss()
            mWaitProgressDialog = null
        }
    }

    override fun hideLoading() {
        super.hideLoading()
        hideWaitingDialog()
    }


}
